package com.cc8w.service;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.springframework.stereotype.Service;

/**
 * 基于TCP协议的socket通讯(客户端)
 * 
 * 1.创建Socket对象,指明需要连接的服务器的地址和端口
 * 2.建立连接后,通过输出流向服务端发送请求信息
 * 3.通过输入流获取服务端相应的信息
 * 4.关闭相应资源
 * 
 * 
 * @author Administrator
 *
 */

@Service
public class SocketService {
	public SocketService() {}
	
	public SocketService(String host,int port) {
		
		try {
			//1.创建客户端Socket,指定服务端地址和端口
			Socket socket = new Socket(host, port);
			//2.获取输出流，向服务端发送信息
			OutputStream os = socket.getOutputStream();//字节流输出
			PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流
			pw.write("111111222");
			pw.flush();
			socket.shutdownOutput();//关闭输出流
			
			//3.关闭其他资源
			pw.close();
			os.close();
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	//创建简单的socket客户端(只给服务端发送信息)
	public void creatSimpleClient(String host,int port) {
		try {
			//1.创建客户端Socket,指定服务端地址和端口
			Socket socket = new Socket(host, port);
			//2.获取输出流，向服务端发送信息
			OutputStream os = socket.getOutputStream();//字节流输出
			PrintWriter pw = new PrintWriter(os);//将输出流包装为打印流
			pw.write("111111222");
			pw.flush();
			
			
			//3.关闭其他资源
			socket.shutdownOutput();//关闭输出流
			//3.1 输出流(相关)
			pw.close();
			os.close();
			
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
		
	}
	
	//创建socket客户端(可以给服务端发信息,也可以接收服务端信息)
	public void createClient(String host,int port) {
		
		try {
			//1.创建socket客户端
			Socket socket = new Socket(host, port);
			//2.给服务端发送消息
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			System.out.println("client: 给服务端发消息->我客户端sss");
			pw.write("我客户端sss3");
			pw.flush();
			socket.shutdownOutput();//关闭输出流
			//3.接收显示服务端响应的消息
			InputStream is = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String info = null;
			while((info = br.readLine())!=null) {
				System.out.println("client: 我收到了server发来的-> "+info);
			}
			socket.shutdownInput();//关闭输入流
			
			//4.关闭资源
			//4.1输入流(相关)
			br.close();
			isr.close();
			is.close();	
			//4.2输出流(相关)
			pw.close();
			os.close();
			//4.3
			socket.close();

			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		
		
	}
	
	
	
}
